<?php
/**
 * Created by PhpStorm.
 * User: jianglong
 * Date: 2017/11/7
 * Time: 下午2:58
 */

namespace app\common\log\distributeRole;

use app\common\log\Base;
use app\manager\admin\ManagerException;
use think\db;

/**
 * 分配用户
 * Class distributeCustomer
 * @package app\common\log\distributeRole
 */
class DistributeCustomer extends Base
{
    public function __construct(array $a_data)
    {
        parent::__construct();
        $this->a_data = $a_data;
    }

    /**
     * 分配一个
     */
    public function disOne()
    {
        $a_data = $this->a_data;
        try{
            //step1 判断客户经理
            $i_managerId = $a_data['manager_id'];
            if (empty($a_data['manager_id']) || empty(Db::name('manager')->find(['id' => $i_managerId]))):
                throw new ManagerException('客户经理不存在！');
            endif;
            //step2 判断客户
            if(empty($a_data['customer_id'])):
                throw new ManagerException('客户不存在！');
            endif;
            $a_customer = Db::name('customer')->find(['id' => $a_data['customer_id']]);
            if(empty($a_customer)):
                throw new ManagerException('客户不存在！');
            endif;
            if($a_customer['manager_id']):
                throw new ManagerException('客户已被分配！');
            endif;
            //step3 记录日志
            $o_model = Db::name('distribute_customer_log');
            //更改用户所属
            if (!Db::name('customer')->where('id', $a_data['customer_id'])->update(['manager_id' => $i_managerId])):
                throw new ManagerException("分配客户失败");
            endif;
            //分配成功
            $a_insertData = [
                'manager_id' => $i_managerId,
                'customer_id' => $a_data['customer_id'],
                'time' => $_SERVER['REQUEST_TIME'],
                'message' => $a_data['message'],
                'operate_id' => $this->i_uid,
                'status' => 1,
                'content' => json_encode($a_data)
            ];
            $o_model->insert($a_insertData);
            return true;
        }catch (ManagerException $e){
            //失败
            $a_insertData = [
                'time' => $_SERVER['REQUEST_TIME'],
                'message' => $a_data['message'],
                'error' => $e->getErrorMsg(),
                'operate_id' => $this->i_uid,
                'status' => 0,
                'content' => json_encode($a_data)
            ];
            $o_model = Db::name('distribute_customer_log');
            $o_model->insert($a_insertData);
            return $e->getErrorMsg();
        }
    }
}